from sadjango import *
from django.db.models import Model
from utils import update_metaclass

class TableDescriptor(object):
    def __init__(self, model):
        self.model = model

    def setup_options(self):
        # TODO
        pass

    def setup(self):
        self.setup_table()
        self.setup_mapper()

    def setup_table(self):
        columns = [f.sa_column for f in self.model._meta.fields]
        self.model.table = Table(self.model._meta.db_table, metadata, *columns)

    def setup_mapper(self):
        properties = dict()
        for field in self.model._meta.fields:
            if field.deferred:
                group = None
                if isinstance(field.deferred, basestring):
                    group = field.deferred
                properties[field.column] = deferred(field.sa_column,
                                                         group=group)

        assign_mapper(context, self.model, self.model.table,
                properties=properties)

def setup(sender=None):
    desc = TableDescriptor(sender)
    desc.setup_options()
    desc.setup()

dispatcher.connect(setup, signal=signals.class_prepared)

